package com.hwtx.form.domain.def.meta;

import cn.hutool.extra.spring.SpringUtil;
import com.hwtx.form.domain.def.GenFormContextHolder;
import com.hwtx.form.domain.repo.ApiRepo;
import com.hwtx.form.domain.service.CommonApiInvoker;
import com.hwtx.form.persistence.entity.ApiDef;
import io.geekidea.boot.framework.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
public class ChainedSelect extends Component.Select {
    public static final String SOURCE = "source";
    public static final String TYPE = "chained-select";

    public ChainedSelect() {
        super(TYPE);
    }

    public static Api getSource(Map<String, Object> ext, List<String> values) {
        return getSource(ext.get(SOURCE), values);
    }

    public static Api getSource(Object sourceCode, List<String> values) {
        if (sourceCode == null) {
            throw new BusinessException("数据源不能为空");
        }
        ApiRepo apiRepo = SpringUtil.getBean(ApiRepo.class);
        ApiDef apiDef = apiRepo.getApiDef(sourceCode.toString());
        if (apiDef == null) {
            throw new BusinessException("数据源不存在,code = " + sourceCode);
        }
        return CommonApiInvoker.getApiUrlWithValues(apiDef, GenFormContextHolder.getDomain(), GenFormContextHolder.getContextPath(), values);
    }

    public static class GroupChainedSelect extends Combo {
        public static FormBase build(String name, String label, boolean multiple, boolean required, List<Component> components) {
            Combo combo = new Combo();
            combo.setName(name);
            combo.setLabel(label);
            combo.setMultiple(multiple);
            combo.setItems(components);
            combo.setRequired(required);
            return combo;
        }
    }
}


